<template>
  <div class="search">
    <van-nav-bar
  title="搜索中心"
  left-arrow
   @click-left="$router.back()"
/>
    <van-search
  show-action
  placeholder="请输入搜索关键词"
  shape="round"
  v-model.trim="keyword"
  @input="getSuggestion"

>
  <template #action>
    <div @click='clickSearch'>搜索</div>
  </template>
</van-search>
  <!-- 联想建议 -->
    <van-cell-group v-if="keyword">
      <van-cell  v-for="(item,index) in handlerSuggestions" :key="item"  icon="search">
          <div v-html="item" @click='clickSuggestion(index)'></div>
      </van-cell>
    </van-cell-group>
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <van-cell-group v-else>
      <van-cell title="历史记录">
      </van-cell>
      <van-cell @click='clickHistory(item)' v-for="(item,index) in hisdory" :key="item" :title="item">
        <van-icon @click.stop='delHistory(index)' name="close" />
      </van-cell>

    </van-cell-group>
    <!-- /搜索历史记录 -->
  </div>
</template>

<script>
import { setHistory, getHistory } from '@/utils/storage'
import { reqGetSearch } from '@/api/search'
export default {
  name: 'Search',
  data () {
    return {
      keyword: '', // 搜索关键字
      suggestion: [],
      hisdory: getHistory() || [],
      timeId: null
    }
  },
  computed: {
    handlerSuggestions () {
      // 创建正则
      const reg = new RegExp(this.keyword, 'gi')
      return this.suggestion.map(item => {
        return item.replace(reg, (value) => {
          return `<span style="color:red">${value}</span>`
        })
      })
    }
  },
  methods: {
    getSuggestion () {
      clearTimeout(this.timeId)
      this.timeId = setTimeout(async () => {
        if (this.keyword === '') {
          this.suggestion = []
          return
        }
        // 调用方法, 发送请求
        const res = await reqGetSearch(this.keyword)
        console.log(res)
        this.suggestion = res.data.data.options
      // console.log(this.suggestion)
      }, 1000)
    },
    // 点击搜索按钮
    clickSearch () {
      if (!this.keyword) return
      // console.log('123')
      this.addHistory(this.keyword)
    },
    // 点击联想推荐
    clickSuggestion (index) {
      // console.log(this.suggestion[index])
      this.addHistory(this.suggestion[index])
    },
    // 添加历史
    addHistory (str) {
      console.log(str)
      const index = this.hisdory.findIndex(item => item === str)
      console.log(index)
      if (index !== -1) {
        // 说明历史记录中已经有了这一项, 应该删除掉
        this.hisdory.splice(index, 1)
      }
      // 追加新历史
      this.hisdory.unshift(str)
      this.$router.push('/result?keyword=' + str)
      // 历史本地存储
      setHistory(this.hisdory)
    },
    // 点击历史跳转
    clickHistory (item) {
      this.addHistory(item)
      this.$router.push('/result?keyword=' + item)
    },
    // 删除历史
    delHistory (index) {
      console.log('qqqq')
      this.hisdory.splice(index, 1)
      // 历史本地存储
      setHistory(this.hisdory)
    }
  }
}
</script>

<style>

</style>
